<script setup lang="ts">
import { h } from 'vue'
import { Edit } from '@element-plus/icons-vue'
import { ElTag } from 'element-plus'
import SearchForm from './components/SearchForm.vue'
import ListModal from './components/ListModal.vue'
import type { TableList } from './types'
import TableLists from '@/components/TableLists/TableLists.vue'
import TdButton from '@/components/TdButton/TdButton.vue'
import 'element-plus/es/components/tag/style/css'
import { uuid } from '@/utils'
import { alarmThresholdApi } from '@/api'

import type { TableColumn } from '@/types'

const loading = ref(true)
const lists = ref<TableList[]>([])
const columns: TableColumn<TableList>[] = reactive([
  {
    key: uuid(),
    label: '告警类型',
    prop: 'alarmThresholdTypeName',
    render({ row }) {
      return row.alarmThresholdTypeName
        ? h(
          ElTag,
          {
            type: 'success',
          },
          () => row.alarmThresholdTypeName,
        )
        : ''
    },
  },
  { key: uuid(), label: '最小值', prop: 'minimumValue' },
  { key: uuid(), label: '最大值', prop: 'maximumValue' },
])

const modalTitle = ref('')
const modalData = ref<Partial<TableList>>({})
const modalRef = ref<InstanceType<typeof ListModal> | null>(
  null,
)

async function queryLists() {
  loading.value = true
  try {
    const { data }
      = await alarmThresholdApi.selectAlarmThreshold()
    lists.value = (data || []).map((v: any) => ({
      ...v,
      minimumValue: Number(v.minimumValue),
      maximumValue: Number(v.maximumValue),
    }))
  }
  finally {
    loading.value = false
  }
}

async function clickSearch() {
  queryLists()
}

async function clickAdd() {
  modalTitle.value = '新增告警阈值'
  modalData.value = {}
  await nextTick()
  modalRef.value?.open()
}

async function clickEdit(row: TableList) {
  modalTitle.value = '编辑告警阈值'
  modalData.value = { ...row }
  await nextTick()
  modalRef.value?.open()
}

onMounted(() => {
  queryLists()
})
</script>

<template>
  <div
    class="padding-sm flex-direction flex align-end container"
  >
    <TableLists
      :loading="loading"
      :lists="lists"
      :columns="columns"
    >
      <template #actions>
        <SearchForm
          @search="clickSearch"
          @add="clickAdd"
        />
      </template>
      <template #operate="{ row }">
        <TdButton
          :icon="Edit"
          title="编辑"
          type="primary"
          @click="clickEdit(row)"
        />
      </template>
    </TableLists>
    <ListModal
      ref="modalRef"
      v-model:data="modalData"
      :modal-title="modalTitle"
      @save-success="queryLists"
    />
  </div>
</template>
